;(function(admin, $) {
	admin.admin_template_setup = {
		init : function() {
			var rem, the_id,
				self = this,
				chooser = $('.widgets-chooser'),
				selectSidebar = chooser.find('.widgets-chooser-sidebars'),
				sidebars = $('div.widgets-sortables'),
				isRTL = !! ( 'undefined' !== typeof isRtl && isRtl );

			$('#widgets-right .sidebar-name').click( function() {
				var $this = $(this),
					$wrap = $this.closest('.widgets-holder-wrap');

				if ( $wrap.hasClass('closed') ) {
					$wrap.removeClass('closed');
					$this.parent().sortable('refresh');
					$this.find('.sidebar-name-arrow').removeClass('fontello-icon-down-open').addClass('fontello-icon-up-open');
				} else {
					$wrap.addClass('closed');
					$this.find('.sidebar-name-arrow').removeClass('fontello-icon-up-open').addClass('fontello-icon-down-open');
				}
			});

			$('#widgets-left .sidebar-name').click( function() {
				$(this).closest('.widgets-holder-wrap').toggleClass('closed');
				if ($(this).find('.sidebar-name-arrow').hasClass('fontello-icon-up-open')) {
					$(this).find('.sidebar-name-arrow').removeClass('fontello-icon-up-open').addClass('fontello-icon-down-open');
				} else {
					$(this).find('.sidebar-name-arrow').removeClass('fontello-icon-down-open').addClass('fontello-icon-up-open');
				}
			});
			
			admin.admin_template_setup.layout_search();

			$(document.body).bind('click.widgets-toggle', function(e) {
				var target = $(e.target),
					css = { 'z-index': 100 },
					widget, inside, targetWidth, widgetWidth, margin;

				if ( target.parents('.widget-top').length && ! target.parents('.id-available-widgets').length ) {
					widget = target.closest('div.widget');
					inside = widget.children('.widget-inside');
					targetWidth = parseInt( widget.find('input.widget-width').val(), 10 ),
					widgetWidth = widget.parent().width();

					if ( inside.is(':hidden') ) {
						if ( targetWidth > 250 && ( targetWidth + 30 > widgetWidth ) && widget.closest('div.widgets-sortables').length ) {
							if ( widget.closest('div.widget-liquid-right').length ) {
								margin = isRTL ? 'margin-right' : 'margin-left';
							} else {
								margin = isRTL ? 'margin-left' : 'margin-right';
							}

							css[ margin ] = widgetWidth - ( targetWidth + 30 ) + 'px';
							widget.css( css );
						}
						widget.addClass( 'open' );
						inside.slideDown('fast');
						widget.find('.widget-action').removeClass('fontello-icon-down-open').addClass('fontello-icon-up-open');
					} else {
						inside.slideUp('fast', function() {
							widget.attr( 'style', '' );
							widget.removeClass( 'open' );
							widget.find('.widget-action').removeClass('fontello-icon-up-open').addClass('fontello-icon-down-open');
						});
					}
					e.preventDefault();
				} else if ( target.hasClass('widget-control-save') ) {
					admin.admin_template_setup.save( target.closest('div.widget'), null, 0 );
					e.preventDefault();
				} else if ( target.hasClass('widget-control-remove') ) {
					admin.admin_template_setup.remove( target.closest('div.widget'), null, 0 );
					target.closest('div.widget').remove();
					e.preventDefault();
				} else if ( target.hasClass('widget-control-close') ) {
					admin.admin_template_setup.close( target.closest('div.widget') );
					e.preventDefault();
				}
			});

			sidebars.children('.widget').each( function() {
				var $this = $(this);

				admin.admin_template_setup.appendTitle( this );

				if ( $this.find( 'p.widget-error' ).length ) {
					$this.find( 'a.widget-action' ).trigger('click');
				}
			});

			$('.id-widget-list').children('.widget').draggable({
				connectToSortable	: 'div.widgets-sortables',
				handle				: '> .widget-top > .widget-title',
				distance			: 2,
				helper				: 'clone',
				zIndex				: 100,
				containment			: 'document',
				start : function( event, ui ) {
					var chooser = $(this).find('.widgets-chooser');

					ui.helper.find('div.widget-description').hide();
					the_id = this.id;

					if ( chooser.length ) {
						/* Hide the chooser and move it out of the widget */
						$( '#wpbody-content' ).append( chooser.hide() );
						/* Delete the cloned chooser from the drag helper */
						ui.helper.find('.widgets-chooser').remove();
						admin.admin_template_setup.clearWidgetSelection();
					}
				},
				stop : function() {
					if ( rem ) {
						$(rem).hide();
					}

					rem = '';
				}
			});

			sidebars.sortable({
				placeholder	: 'widget-placeholder',
				items		: '> .widget',
				handle		: '> .widget-top > .widget-title',
				cursor		: 'move',
				distance	: 2,
				containment	: 'document',
				start : function( event, ui ) {
					var height, $this = $(this),
						$wrap = $this.parent(),
						inside = ui.item.children('.widget-inside');

					if ( inside.css('display') === 'block' ) {
						inside.hide();
						$(this).sortable('refreshPositions');
					}

					if ( ! $wrap.hasClass('closed') ) {
						height = ui.item.hasClass('ui-draggable') ? $this.height() : 1 + $this.height();
						$this.css( 'min-height', height + 'px' );
					}
				},

				stop : function( event, ui ) {
					var addNew, widgetNumber, $sidebar, $children, child, item, region
						$widget = ui.item,
						id = the_id;
					
					if ( $widget.hasClass('deleting') ) {
						admin.admin_template_setup.remove( $widget, null, 1 );
						$widget.remove();
						return;
					}

					addNew = $widget.find('input.add_new').val();
					widgetNumber = $widget.find('input.multi_number').val();
					// console.log(addNew);exit();
					$widget.attr( 'style', '' ).removeClass('ui-draggable');
					the_id = '';
					console.log(addNew);
					//拖拽添加widget
					if ( addNew ) {
						if ( 'multi' === addNew ) {
							$widget.html(
								$widget.html().replace( /<[^<>]+>/g, function( tag ) {
									return tag.replace( /__i__|%i%/g, widgetNumber );
								})
							);

							$widget.attr( 'id', id.replace( '__i__', widgetNumber ) );
							widgetNumber++;

							$( 'div#' + id ).find( 'input.multi_number' ).val( widgetNumber );
						} else if ( 'single' === addNew ) {
							$widget.attr( 'id', 'new-' + id );
							rem = 'div#' + id;
						}

						$sidebar = $widget.parent();
						region = $sidebar.find( '.sidebar-name h3' ).text()
						region = $.trim(region);
						admin.admin_template_setup.save( $widget, region, 1 );

						$widget.find('input.add_new').val('');
						$( document ).trigger( 'widget-added', [ $widget ] );
					}

					
					// $sidebar = $widget.parent();
					// region = $sidebar.find( '.sidebar-name h3' ).text()
					// region = $.trim(region);
					// admin.admin_template_setup.save( $widget, region, 1 );

					$sidebar = $widget.parent();

					if ( $sidebar.parent().hasClass('closed') ) {
						$sidebar.parent().removeClass('closed');
						$children = $sidebar.children('.widget');

						if ( $children.length > 1 ) {
							child = $children.get(0);
							item = $widget.get(0);

							if ( child.id && item.id && child.id !== item.id ) {
								$( child ).before( $widget );
							}
						}
					}

					if ( addNew ) {
						$widget.find( 'a.widget-action' ).trigger('click');
					} else {
						admin.admin_template_setup.saveOrder( $sidebar.attr('id') );
					}
				},

				activate : function() {
					$(this).parent().addClass( 'widget-hover' );
				},

				deactivate : function() {
					$(this).css( 'min-height', '' ).parent().removeClass( 'widget-hover' );
				},

				receive : function( event, ui ) {
					var $sender = $( ui.sender );

					if ( this.id.indexOf('orphaned_widgets') > -1 ) {
						$sender.sortable('cancel');
						return;
					}

					// if ( $sender.attr('id').indexOf('orphaned_widgets') > -1 && ! $sender.children('.widget').length ) {
					// 	$sender.parents('.orphan-sidebar').slideUp( 400, function() { $(this).remove(); } );
					// }
				}
			}).sortable( 'option', 'connectWith', 'div.widgets-sortables' );

			$('.id-available-widgets').droppable({
				tolerance : 'pointer',
				accept : function(o) {
					return !$(o).parent().hasClass('id-widget-list');
				},
				drop : function(e,ui) {
					ui.draggable.addClass('deleting');
					$('.id-removing-widget').hide().children('span').html('');
				},
				over : function(e,ui) {
					ui.draggable.addClass('deleting');
					$('div.widget-placeholder').hide();

					if ( ui.draggable.hasClass('ui-sortable-helper') ) {
						$('.id-removing-widget').show().children('span')
						.html( ui.draggable.find('div.widget-title').children('h4').html() );
					}
				},
				out : function(e,ui) {
					ui.draggable.removeClass('deleting');
					$('div.widget-placeholder').show();
					$('.id-removing-widget').hide().children('span').html('');
				}
			});

			$( '#widgets-right .widgets-holder-wrap' ).each( function( index, element ) {
				var $element = $( element ),
					name = $element.find( '.sidebar-name h3' ).text(),
					id = $element.find( '.widgets-sortables' ).attr( 'id' ),
					li = $('<li tabindex="0">').text( $.trim( name ) );
				console.log(selectSidebar.next().find('button'));
				console.log($element.find( '.widgets-sortables' ).attr( 'id' ));
				if ( ! $element.find( '.widgets-sortables' ).attr( 'id' ) ) {
					selectSidebar.hide();
					selectSidebar.next().find('button').each( function ( index, element ) {
						var $element = $( element );
						console.log($element);
						$element.attr('disabled', true);
					});
					return;
				}
				
				if ( index === 0 ) {
					li.addClass( 'widgets-chooser-selected' );
				}

				selectSidebar.append( li );
				li.data( 'sidebarId', id );
			});

			/*左侧子选项的点击事件 */
			$( '.id-available-widgets .widget .widget-title' ).on( 'click.widgets-chooser', function() {
				var $widget = $(this).closest( '.widget' );

				if ( $widget.hasClass( 'widget-in-question' ) || $( '#widgets-left' ).hasClass( 'chooser' ) ) {
					admin.admin_template_setup.closeChooser();
				} else {
					admin.admin_template_setup.clearWidgetSelection();
					$( '#widgets-left' ).addClass( 'chooser' );
					$widget.addClass( 'widget-in-question' ).children( '.widget-description' ).after( chooser );

					chooser.slideDown( 300, function() {
						selectSidebar.find('.widgets-chooser-selected').focus();
					});

					selectSidebar.find( 'li' ).on( 'focusin.widgets-chooser', function() {
						selectSidebar.find('.widgets-chooser-selected').removeClass( 'widgets-chooser-selected' );
						$(this).addClass( 'widgets-chooser-selected' );
					} );
				}
			});

			/* 添加节点到右侧区域 */
			chooser.on( 'click.widgets-chooser', function( event ) {
				var $target = $( event.target );

				if ( $target.hasClass('btn-info') ) {
					admin.admin_template_setup.addWidget( chooser );
					admin.admin_template_setup.closeChooser();
				} else if ( $target.hasClass('btn-secondary') ) {
					admin.admin_template_setup.closeChooser();
				}
			}).on( 'keyup.widgets-chooser', function( event ) {
				if ( event.which === $.ui.keyCode.ENTER ) {
					if ( $( event.target ).hasClass('btn-secondary') ) {
						admin.admin_template_setup.closeChooser();
					} else {
						admin.admin_template_setup.addWidget( chooser );
						admin.admin_template_setup.closeChooser();
					}
				} else if ( event.which === $.ui.keyCode.ESCAPE ) {
					admin.admin_template_setup.closeChooser();
				}
			});
		},
		
		layout_search : function() {
            //li搜索筛选功能
            $('#ms-search').quicksearch(
                $('.ms-elem-selectable', '#ms-custom-navigation' ),
                {
                    onAfter : function(){
                        $('.ms-group').each(function(index) {
                            $(this).find('.isShow').length ? $(this).css('display','block') : $(this).css('display','none');
                        });
                        return;
                    },
                    show: function () {
                        this.style.display = "";
                        $(this).addClass('isShow');
                    },
                    hide: function () {
                        this.style.display = "none";
                        $(this).removeClass('isShow');
                    },
                }
            );
        },

		saveOrder : function(sidebarId) {
			var data = {};

			if ( sidebarId ) {
				$( '#' + sidebarId ).find('.spinner:first').css('display', 'inline-block');
			}

			$('div.widgets-sortables').each( function() {
				if ( $(this).sortable ) {
					data['sidebars[' + $(this).attr('data-name') + ']'] = $(this).sortable('toArray').join(',');
				}
			});
			var ajaxurl = $('#ecjia_inactive_widgets').attr('data-url');
			data['template_file'] = $('#ecjia_inactive_widgets').attr('data-file');

			$.post( ajaxurl, data, function() {
				$('.spinner').hide();
			});
		},
		
		remove : function( widget, region, order ) {
			var sidebarId = widget.closest('div.widgets-sortables').attr('id'),
				data = widget.find('form').serialize(),
				templateFile = widget.closest('div.widgets-sortables').attr('data-file');

			widget = $(widget);
			$('.spinner', widget).show();

			data += '&' + $.param({ "template_file" : templateFile });

			var ajaxurl = widget.find('.widget-control-remove').attr('data-url');
			$.post(ajaxurl, data, function(data) {
				ecjia.admin.showmessage(data);
			});
		},

		save : function( widget, region, order ) {
			var sidebarId = widget.closest('div.widgets-sortables').attr('id'),
				data = widget.find('form').serialize(), 
				templateFile = widget.closest('div.widgets-sortables').attr('data-file');
			widget = $(widget);
			$('.spinner', widget).show();

			data += '&' + $.param({ "template_file" : templateFile });

			if ( region ) {
				data += '&' + $.param({ "widget-region" : region });
			}
			
			var ajaxurl = widget.find('form').attr('action');
			$.post(ajaxurl, data, function(data) {
				ecjia.admin.showmessage(data);
			});
		},

		appendTitle : function(widget) {
			// console.log('function appendTitle');
		},

		close : function(widget) {
			widget.children('.widget-inside').slideUp('fast', function() {
				widget.attr( 'style', '' );
			});
		},

		addWidget : function( chooser ) {
			var widget, widgetId, add, n, viewportTop, viewportBottom, sidebarBounds,
				sidebarId = chooser.find( '.widgets-chooser-selected' ).data('sidebarId'),
				sidebar = $( '#' + sidebarId ),
				region = chooser.find( '.widgets-chooser-selected' ).html();

			widget = $('.id-available-widgets').find('.widget-in-question').clone();

			widgetId = widget.attr('id');
			add = widget.find( 'input.add_new' ).val();
			n = widget.find( 'input.multi_number' ).val();

			/* Remove the cloned chooser from the widget */
			widget.find('.widgets-chooser').remove();

			if ( 'multi' === add ) {
			// 	widget.html(
			// 		widget.html().replace( /<[^<>]+>/g, function(m) {
			// 			return m.replace( /__i__|%i%/g, n );
			// 		})
			// 	);

			// 	widget.attr( 'id', widgetId.replace( '__i__', n ) );
			// 	n++;
			// 	$( '#' + widgetId ).find('input.multi_number').val(n);
			} else if ( 'single' === add ) {
			// 	widget.attr( 'id', 'new-' + widgetId );
				$( '#' + widgetId ).hide();
			}

			sidebar.closest( '.widgets-holder-wrap' ).removeClass('closed');

			sidebar.append( widget );
			sidebar.sortable('refresh');

			admin.admin_template_setup.save( widget, region, 1 );
			widget.find( 'input.add_new' ).val('');

			$( document ).trigger( 'widget-added', [ widget ] );

			viewportTop = $(window).scrollTop();
			viewportBottom = viewportTop + $(window).height();
			sidebarBounds = sidebar.offset();

			sidebarBounds.bottom = sidebarBounds.top + sidebar.outerHeight();

			if ( viewportTop > sidebarBounds.bottom || viewportBottom < sidebarBounds.top ) {
				$( 'html, body' ).animate({
					scrollTop : sidebarBounds.top - 130
				}, 200 );
			}

			window.setTimeout( function() {
				widget.find( '.widget-title' ).trigger('click');
			}, 250 );

			admin.admin_template_setup.saveOrder( sidebarId );
		},

		closeChooser : function() {
			var self = this;

			$( '.widgets-chooser' ).slideUp( 200, function() {
				$( '#wpbody-content' ).append( this );
				admin.admin_template_setup.clearWidgetSelection();
			});
		},

		clearWidgetSelection : function() {
			$( '#widgets-left' ).removeClass( 'chooser' );
			$( '.widget-in-question' ).removeClass( 'widget-in-question' );
		}

	};

	$(document).on('submit', 'form[name="select_template"]', function(e) {
		var $this = $(this);
		var url = $this.attr('action') + '&template_file=' + $this.find('select[name="template_file"]').val();
		e.preventDefault();
		ecjia.pjax(url);
	})

})(ecjia.admin, jQuery);
